import { Article } from '@libs/db/models/article.model';
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
import { ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';

// post 和 put 请求添加参数
class articlePostDto {
  @ApiProperty({ description: '文章标题'})
  title: string;
  @ApiProperty({ description: '文章作者'})
  up: string;
  @ApiProperty({ description: '文章内容'})
  content: string;
  @ApiProperty({ description: '文章类型'})
  category: string;
}

// class articleGetDto {
//   @ApiProperty({description: '文章的当前页'})
//   page: string;
//   @ApiProperty({description: '文章页面显示的数量'})
//   pagesize: number;
//   @ApiProperty({description: '文章是否排序'})
//   sort: string;
//   @ApiProperty({description: '文章模糊搜索'})
//   name: string;
// }

@ApiTags('文章接口')
@Controller('articles')
export class ArticlesController {
  constructor(
    @InjectModel(Article) private readonly ArticleMode: ModelType<Article>
  ) {}

  @Get('page/')
  @ApiOperation({summary: '文章列表'})
  async slslct(@Query() pages: any) {
    let {page, pagesize, sort, name = ''} = pages;

    const total = await this.ArticleMode.countDocuments({$or: [{"title": {"$regex": name}}]});

    const skip: number = page * pagesize - pagesize;
    pagesize = pagesize - 0;

    const data = await this.ArticleMode.find({$or: [{"title": {"$regex": name}}]}).skip(skip).limit(pagesize).sort({_id: sort});
    return  {
      total,
      content: data
    }
  }

  @Get(':id')
  @ApiOperation({summary: '根据id查找文章'})
  async selectId(@Param('id') id: string) {
    const data = await this.ArticleMode.findById(id);
    return {
      status: 200,
      data
    }
  }

  @Post()
  @ApiOperation({summary: '创建文章'})
  async create(@Body() articlePostDto: articlePostDto) {
    await this.ArticleMode.create(articlePostDto);
    return { success: '创建成功' }
  }

  @Put(':id')
  @ApiOperation({summary: '修改文章'})
  async update(@Param('id') id: string, @Body() articlePostDto: articlePostDto ) {
    await this.ArticleMode.updateOne({_id: id}, articlePostDto);
    return { success: '修改成功' }
  }

  @Delete(':id')
  @ApiOperation({summary: '删除文章'})
  async remove(@Param('id') id: string) {
    await this.ArticleMode.findOneAndDelete({_id: id});
    return { success: '删除成功' }
  }
}
